<template>
  <el-dialog :title="title" width="800px" :visible.sync="visible" destroy-on-close @close="closeCallback">
    <div class="card">
    <p class="title"><i class="fa fa-th-large fa-lg"></i>广告信息</p>
    <el-form :model="adsForm" status-icon :rules="rules" ref="adsForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="公司名称" prop="adcompany">
        <el-input v-model="adsForm.adcompany" autocomplete="off" clearable></el-input>
      </el-form-item>
      <el-form-item label="广告收入" prop="adincome">
        <el-input-number v-model="adsForm.adincome" :precision="2" :step="1.0" :min="0.0" :max="100000" autocomplete="off"></el-input-number>
      </el-form-item>
      <el-form-item label="广告有效期" prop="adtime">
        <div class="block">
          <el-date-picker
            v-model="adsForm.adtime"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </div>
      </el-form-item>
      <el-form-item label="外接URL" prop="adlink">
        <el-input placeholder="请输入URL" v-model="adsForm.adlink" autocomplete="off" clearable>
          <template slot="prepend">Http://</template>
        </el-input>
      </el-form-item>
      <el-form-item label="广告图片" prop="adimage">
        <el-upload
          class="avatar-uploader"
          action=""
          ref="uploadFile"
          :show-file-list="false"
          :http-request="uploadFileMethod"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="备注" prop="adremarks">
        <el-input type="textarea" placeholder="请输入备注" v-model="adsForm.adremarks" maxlength="20" show-word-limit></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('adsForm')">确 定</el-button>
        <el-button @click="resetForm('adsForm')">重 置</el-button>
      </el-form-item>
    </el-form>
    </div>
  </el-dialog>
</template>

<script>
import form from "../../../api/apis/corporate/ads/ads"
import execute from "../../../utils/constant/execute"
import stateCode from "../../../utils/constant/stateCode"
import baseConfig from "../../../utils/constant/baseConfig"

export default {
  name: "adsInfo",
  props: {
    title: { type: String, default: "广告信息" },
    dialogVisible: { type: Boolean, default: false }
  },
  data () {
    var checkAds = (rule, value, callback) => {
      form.fetchCheckAds(value).then((res) => {
        if (res.data.code === stateCode.OPRATION_FAILED) {
          callback(new Error(res.data.msg))
        } else if (res.data.code === stateCode.OPRATION_SUCCESS) {
          callback()
        }
      })
    }
    var validatorFigure = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error("金额不能小于0"))
      } else {
        callback()
      }
    }
    return {
      visible: this.dialogVisible,
      adsForm: {
        adcompany: "",
        adimage: "",
        adlink: "",
        adtime: "",
        adincome: "",
        adremarks: ""
      },
      imageUrl: "",
      rules: {
        adcompany: [
          { required: true, message: "请输入公司名称", trigger: "blur" },
          { validator: checkAds, trigger: "blur" }
        ],
        adlink: [
          { required: true, message: "请输入广告外接URL", trigger: "blur" }
        ],
        adtime: [
          { required: true, message: "请输入广告有效期", trigger: "blur" }
        ],
        adincome: [
          { validator: validatorFigure, trigger: ["blur", "change"] },
          { required: true, message: "请输入费用", trigger: "blur" }
        ]
      }
    }
  },
  methods: {
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === "image/jpeg"
      const isPNG = file.type === "image/png"
      const isLt500K = file.size / 1024 < 500

      let flag = true
      if (!(isJPG || isPNG)) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!")
        flag = false
      }
      if (!isLt500K) {
        this.$message.error("上传头像图片大小不能超过 500KB!")
        flag = false
      }
      return flag
    },
    uploadFileMethod (fileObj) {
      let imageData = new FormData()
      let file = fileObj.file
      let fileName = file.uid + file.name.substring(file.name.lastIndexOf(".")).toLowerCase()
      imageData.append("flimage", file, fileName)

      form.fetchUploadImage(imageData).then((res) => {
        if (res.data.code === stateCode.OPRATION_SUCCESS) {
          this.$message({ type: execute.SUCCESS, message: res.data.msg })
          this.imageUrl = baseConfig.baseUrl + "image/" + fileName
          this.adsForm.adimage = fileName
        } else {
          this.$message({ type: execute.WARNING, message: res.data.msg })
        }
      }).catch((res) => {
        this.$message({
          showClose: true,
          message: res,
          type: execute.ERROR
        })
      })
    },
    closeCallback () {
      this.$emit("successCallback")
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formData = {
            adcompany: this.adsForm.adcompany,
            adimage: this.adsForm.adimage,
            adlink: this.adsForm.adlink,
            adtime: this.adsForm.adtime,
            adincome: this.adsForm.adincome,
            adremarks: this.adsForm.adremarks
          }
          form.fetchAddAds(formData).then((res) => {
            if (res.data.code === stateCode.OPRATION_SUCCESS) {
              this.$message({ type: execute.SUCCESS, message: res.data.msg })
            } else {
              this.$message({ type: execute.WARNING, message: res.data.msg })
            }
            this.$emit("loadData")
          }).catch((res) => {
            this.$message({
              showClose: true,
              message: res.data.msg,
              type: execute.ERROR
            })
          })
          this.visible = false
        } else {
          return false
        }
      })
    }
  },
  mounted () {
  }
}
</script>
<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .demo-ruleForm {
    width: 460px;
    padding-top: 25px;
  }
  .el-select {
    width: 100%;
  }
  .card {
    width: 560px;
    padding-bottom: 15px;
    margin: 0px auto;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
